package com.wushi.lenovo.asia5b.app_ui.other.dialog;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mvp.base.BaseApplication;
import com.mvp.base.BaseDialog;
import com.mvp.images.ImageHelper;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.other.ShareBean;
import com.wushi.lenovo.asia5b.app_utils.helper.UriHelper;
import com.wushi.lenovo.asia5b.wxapi.WXUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhangyuncai on 2018/12/18.
 */
public class ShareDialog extends BaseDialog {
    @BindView(R.id.et_dialog_link)
    TextView et_dialog_link;
    @BindView(R.id.ll_share_copn_vessel)
    LinearLayout ll_share_copn_vessel;
    private Activity activity;
    private ShareBean shareBean;

    public ShareDialog(Activity activity, ShareBean shareBean) {
        super(activity);
        this.activity = activity;
        this.shareBean = shareBean;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.dialog_share;
    }

    @Override
    protected void initView() {
        if (shareBean.shareType == ShareBean.GOODS) {
            et_dialog_link.setText(shareBean.getShareUrl());
            ll_share_copn_vessel.setVisibility(View.VISIBLE);
        } else {
            ll_share_copn_vessel.setVisibility(View.GONE);
        }
    }


    @Override
    protected void initListener() {

    }

    //分享facebook
    private void shareFacebook() {
        share("com.facebook.katana");
    }

    //分享messenger
    private void shareMessenger() {
        share("com.facebook.orca");
    }

    //分享微信
    private void shareWechat() {
//                Intent sendIntent = new Intent();
//                sendIntent.setAction(Intent.ACTION_SEND);
//                sendIntent.putExtra(Intent.EXTRA_TEXT, shareBean.getShareUrl());
//                sendIntent.setType("text/plain");
//                sendIntent.setPackage("com.tencent.mm");
//                activity.startActivity(sendIntent);
        if (shareBean.shareType == ShareBean.GOODS) {
            shareWeixin();
        } else {
            share("com.tencent.mm");
        }
    }

    //分享whatsapp
    private void shareWhatsapp() {
        share("com.whatsapp");
    }

    private void share(String pagename) {
        String fullPackageName = getFullPackageName(pagename);
        if (TextUtils.isEmpty(fullPackageName)) {
            ToastUtil.showToast(getString(R.string.not_app));
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage(pagename);
        if (shareBean.shareType == ShareBean.GOODS) {
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, shareBean.getShareUrl());
        } else if (shareBean.shareType == ShareBean.IMG) {
            File file = new File(shareBean.getImgFilePath());
            if (file.exists()) {
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_STREAM,
                        UriHelper.getUri(file));
            }
        }
        activity.startActivity(Intent.createChooser(intent, "share"));
    }


    @OnClick({R.id.iv_dialog_close, R.id.bt_dialog_ok,
            R.id.tv_facebook, R.id.iv_messenger, R.id.iv_wechat, R.id.iv_whatsapp})
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.tv_facebook: {
                shareFacebook();
            }
            break;
            case R.id.iv_messenger: {
                shareMessenger();
            }
            break;
            case R.id.iv_dialog_close:
                break;
            case R.id.iv_wechat: {
                shareWechat();
            }
            break;
            case R.id.iv_whatsapp: {
                shareWhatsapp();
            }
            break;
            case R.id.bt_dialog_ok:
                ClipboardManager systemService = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                systemService.setPrimaryClip(ClipData.newPlainText("wsy", shareBean.getShareUrl()));
                String string = getString(R.string.copied);
                ToastUtil.showToast(string);
                break;
        }

        dismiss();
    }

    private String getFullPackageName(String packageName) {
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        List<ResolveInfo> resInfo = activity.getPackageManager().queryIntentActivities(
                intent, 0);
        if (!resInfo.isEmpty()) {
            for (ResolveInfo info : resInfo) {
                if (info.activityInfo.packageName.toLowerCase().contains(
                        packageName)
                        || info.activityInfo.name.toLowerCase().contains(
                        packageName)) {
                    return info.activityInfo.packageName;
                }
            }
        }
        return null;
    }

    private void shareWeixin() {
        Observable.just(1)
                .map(new Function<Integer, Bitmap>() {
                    @Override
                    public Bitmap apply(Integer Integer) throws Exception {
                        String imageUrl = ImageHelper.addImageDomain(shareBean.getImgUrl());
                        return Glide.with(BaseApplication.sContext).asBitmap().load(imageUrl).submit().get();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(bitmap -> {
                    shareBean.setBitmap(bitmap);
                    new WXUtils().share(activity, shareBean);
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }

    @Override
    protected int getWidthStyle() {
        return getScreenWidth(0.8f);
    }
}
